{% extends "base.html" %}

{% block title %}创建文档 - Ruiyun Cloud{% endblock %}

{% block content %}
<div class="create-page">
    <div class="page-header">
        <h1>📝 创建新文档</h1>
        <p>通过文本输入或上传文件创建文档</p>
    </div>

    <form method="POST" action="{{ url_for('admin.create') }}" enctype="multipart/form-data" class="create-form">
        <!-- Title Field -->
        <div class="form-group">
            <label for="title">文档标题 <span class="required">*</span></label>
            <input
                type="text"
                id="title"
                name="title"
                class="form-control"
                placeholder="请输入文档标题"
                maxlength="200"
                required
            >
            <small class="form-text">最多200个字符</small>
        </div>

        <!-- Category Field -->
        <div class="form-group">
            <label for="category">分类</label>
            <input
                type="text"
                id="category"
                name="category"
                class="form-control"
                placeholder="例如：API文档、使用指南、发布说明等"
                maxlength="100"
                list="category-suggestions"
            >
            <datalist id="category-suggestions">
                <!-- Will be populated dynamically -->
            </datalist>
            <small class="form-text">选填，相同分类的文档会自动归类显示</small>
        </div>

        <!-- Content Input Tabs -->
        <div class="form-tabs">
            <button type="button" class="tab-btn active" data-tab="text-input">
                📝 文本输入
            </button>
            <button type="button" class="tab-btn" data-tab="rich-editor">
                ✨ 富文本编辑器
            </button>
            <button type="button" class="tab-btn" data-tab="file-upload">
                📁 文件上传
            </button>
        </div>

        <!-- Text Input Tab -->
        <div id="text-input" class="tab-content active">
            <div class="form-group">
                <label for="format">文档格式</label>
                <select id="format" name="format" class="form-control">
                    <option value="markdown" selected>Markdown</option>
                    <option value="html">HTML</option>
                    <option value="text">Plain Text</option>
                </select>
            </div>

            <div class="form-group">
                <label for="content">文档内容</label>
                <textarea
                    id="content"
                    name="content"
                    class="form-control textarea-large"
                    placeholder="请输入文档内容...&#10;&#10;Markdown示例：&#10;# 标题&#10;## 二级标题&#10;&#10;这是一段文字。**粗体** *斜体*&#10;&#10;- 列表项1&#10;- 列表项2"
                    rows="20"
                ></textarea>
                <small class="form-text">
                    支持Markdown语法、HTML标签或纯文本
                </small>
            </div>
        </div>

        <!-- Rich Editor Tab -->
        <div id="rich-editor" class="tab-content">
            <div class="form-group">
                <label>富文本编辑器（支持图片粘贴）</label>
                <div id="quill-editor" style="height: 500px; background: white;"></div>
                <textarea id="rich-content" name="rich_content" style="display:none;"></textarea>
                <small class="form-text">
                    支持直接粘贴图片（Ctrl+V）、拖拽上传图片
                </small>
            </div>
        </div>

        <!-- File Upload Tab -->
        <div id="file-upload" class="tab-content">
            <div class="form-group">
                <label for="file">选择文件</label>
                <div class="file-upload-area">
                    <input
                        type="file"
                        id="file"
                        name="file"
                        class="file-input"
                        accept=".md,.html,.txt"
                    >
                    <div class="file-upload-label">
                        <div class="upload-icon">📁</div>
                        <div class="upload-text">
                            点击选择文件或拖拽到此处
                        </div>
                        <div class="upload-hint">
                            支持 .md, .html, .txt 文件，最大10MB
                        </div>
                    </div>
                    <div class="file-name-display"></div>
                </div>
            </div>
        </div>

        <!-- Form Actions -->
        <div class="form-actions">
            <button type="submit" class="btn btn-primary btn-lg">
                ✓ 创建文档
            </button>
            <a href="{{ url_for('admin.dashboard') }}" class="btn btn-secondary btn-lg">
                ✕ 取消
            </a>
        </div>
    </form>
</div>
{% endblock %}

{% block extra_css %}
<!-- Quill.js CSS - 使用本地静态文件 -->
<link href="{{ url_for('static', filename='css/quill.snow.css') }}" rel="stylesheet">
<style>
    .create-page {
        max-width: 900px;
        margin: 0 auto;
    }

    .create-form {
        background: white;
        padding: 2rem;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }

    .form-group {
        margin-bottom: 1.5rem;
    }

    .form-group label {
        display: block;
        margin-bottom: 0.5rem;
        font-weight: 600;
        color: #333;
    }

    .required {
        color: #f5576c;
    }

    .form-control {
        width: 100%;
        padding: 0.75rem;
        border: 1px solid #ddd;
        border-radius: 5px;
        font-size: 1rem;
        transition: border-color 0.3s, box-shadow 0.3s;
    }

    .form-control:focus {
        outline: none;
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    .textarea-large {
        font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
        resize: vertical;
        min-height: 400px;
    }

    .form-text {
        display: block;
        margin-top: 0.25rem;
        font-size: 0.875rem;
        color: #666;
    }

    /* Tabs */
    .form-tabs {
        display: flex;
        gap: 0.5rem;
        margin-bottom: 1.5rem;
        border-bottom: 2px solid #e9ecef;
    }

    .tab-btn {
        padding: 0.75rem 1.5rem;
        background: none;
        border: none;
        border-bottom: 2px solid transparent;
        font-size: 1rem;
        font-weight: 500;
        color: #666;
        cursor: pointer;
        transition: all 0.3s;
        margin-bottom: -2px;
    }

    .tab-btn:hover {
        color: #667eea;
    }

    .tab-btn.active {
        color: #667eea;
        border-bottom-color: #667eea;
    }

    .tab-content {
        display: none;
    }

    .tab-content.active {
        display: block;
    }

    /* File Upload */
    .file-upload-area {
        position: relative;
        border: 2px dashed #ddd;
        border-radius: 8px;
        padding: 3rem 2rem;
        text-align: center;
        transition: border-color 0.3s;
        cursor: pointer;
    }

    .file-upload-area:hover {
        border-color: #667eea;
    }

    .file-input {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
        cursor: pointer;
    }

    .upload-icon {
        font-size: 4rem;
        margin-bottom: 1rem;
    }

    .upload-text {
        font-size: 1.1rem;
        font-weight: 500;
        color: #333;
        margin-bottom: 0.5rem;
    }

    .upload-hint {
        font-size: 0.9rem;
        color: #666;
    }

    .file-name-display {
        margin-top: 1rem;
        font-weight: 500;
        color: #667eea;
    }

    /* Form Actions */
    .form-actions {
        display: flex;
        gap: 1rem;
        justify-content: flex-end;
        margin-top: 2rem;
        padding-top: 1.5rem;
        border-top: 1px solid #e9ecef;
    }

    .btn-lg {
        padding: 0.875rem 2rem;
        font-size: 1.1rem;
    }
</style>
{% endblock %}

{% block extra_js %}
<!-- Quill.js - 使用本地静态文件 -->
<script src="{{ url_for('static', filename='js/quill.js') }}"></script>
<script>
    // 等待DOM加载完成
    document.addEventListener('DOMContentLoaded', function() {
        // 检查Quill是否加载成功
        if (typeof Quill === 'undefined') {
            console.error('Quill.js failed to load from CDN');
            alert('富文本编辑器加载失败，请刷新页面重试或使用文本输入方式');
            return;
        }

        // Initialize Quill editor
        var quill = new Quill('#quill-editor', {
        theme: 'snow',
        modules: {
            toolbar: [
                [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
                ['bold', 'italic', 'underline', 'strike'],
                ['blockquote', 'code-block'],
                [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                [{ 'color': [] }, { 'background': [] }],
                [{ 'align': [] }],
                ['link', 'image'],
                ['clean']
            ]
        }
    });

    // Convert images to base64
    quill.getModule('toolbar').addHandler('image', () => {
        const input = document.createElement('input');
        input.setAttribute('type', 'file');
        input.setAttribute('accept', 'image/*');
        input.click();

        input.onchange = () => {
            const file = input.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    const range = quill.getSelection();
                    quill.insertEmbed(range.index, 'image', e.target.result);
                };
                reader.readAsDataURL(file);
            }
        };
    });

    // Handle paste images
    quill.root.addEventListener('paste', (e) => {
        if (e.clipboardData && e.clipboardData.items) {
            const items = e.clipboardData.items;
            for (let i = 0; i < items.length; i++) {
                if (items[i].type.indexOf('image') !== -1) {
                    e.preventDefault();
                    const blob = items[i].getAsFile();
                    const reader = new FileReader();
                    reader.onload = (event) => {
                        const range = quill.getSelection();
                        quill.insertEmbed(range.index, 'image', event.target.result);
                    };
                    reader.readAsDataURL(blob);
                }
            }
        }
    });

    // Tab switching
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const tabName = this.dataset.tab;

            // Update tab buttons
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');

            // Update tab content
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            document.getElementById(tabName).classList.add('active');

            // Clear other inputs
            if (tabName === 'text-input') {
                document.getElementById('file').value = '';
                document.querySelector('.file-name-display').textContent = '';
                document.getElementById('rich-content').value = '';
            } else if (tabName === 'rich-editor') {
                document.getElementById('content').value = '';
                document.getElementById('file').value = '';
                document.querySelector('.file-name-display').textContent = '';
            } else {
                document.getElementById('content').value = '';
                document.getElementById('rich-content').value = '';
            }
        });
    });

    // File input display
    document.getElementById('file').addEventListener('change', function() {
        const fileName = this.files[0] ? this.files[0].name : '';
        document.querySelector('.file-name-display').textContent = fileName ? `已选择: ${fileName}` : '';
    });

    // Form validation and rich editor content
    document.querySelector('.create-form').addEventListener('submit', function(e) {
        const title = document.getElementById('title').value.trim();
        const content = document.getElementById('content').value.trim();
        const richContent = quill.root.innerHTML;
        const file = document.getElementById('file').files[0];

        // Get active tab
        const activeTab = document.querySelector('.tab-content.active').id;

        if (!title) {
            alert('请输入文档标题');
            e.preventDefault();
            return;
        }

        if (activeTab === 'rich-editor') {
            // Use rich editor content
            if (richContent.trim() === '<p><br></p>' || richContent.trim() === '') {
                alert('请输入文档内容');
                e.preventDefault();
                return;
            }
            document.getElementById('rich-content').value = richContent;
            // Clear other fields
            document.getElementById('content').value = '';
            document.getElementById('file').value = '';
        } else if (activeTab === 'text-input') {
            if (!content) {
                alert('请输入文档内容');
                e.preventDefault();
                return;
            }
            document.getElementById('rich-content').value = '';
        } else if (activeTab === 'file-upload') {
            if (!file) {
                alert('请选择文件');
                e.preventDefault();
                return;
            }
            document.getElementById('rich-content').value = '';
        }
    });

    }); // End of DOMContentLoaded
</script>
{% endblock %}
